package com.atguigu.gulimail.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NostockException;
import com.atguigu.common.service.order.OrderRPCService;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimail.ware.dao.WareSkuDao;
import com.atguigu.gulimail.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimail.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimail.ware.entity.WareSkuEntity;
import com.atguigu.gulimail.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimail.ware.service.WareOrderTaskService;
import com.atguigu.gulimail.ware.service.WareSkuService;
import com.atguigu.gulimail.ware.vo.OrderItemVo;
import com.atguigu.gulimail.ware.vo.OrderVo;
import com.atguigu.gulimail.ware.vo.WareSkuLockVo;
import com.atguigu.gulimail.ware.vo.mq.StockLockedTo;
import com.atguigu.gulimail.ware.vo.mq.stockDetailTo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Data;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    WareOrderTaskService wareOrderTaskService;

    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    RabbitTemplate rabbitTemplate;


    @DubboReference(check = false)
    OrderRPCService orderRPCService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                new QueryWrapper<WareSkuEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void addWareStack(Long skuId, Long wareId, Integer skuNum) {

        List<WareSkuEntity> wareSkuEntities = this.baseMapper.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));

        if(wareSkuEntities == null || wareSkuEntities.size() == 0){
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);

            try{

                //TODO 这里由于前期使用的是openfeign 后期更改为dubbo所以注释了，有空我会在写一下
//                R info = productOpenFeignService.info(skuId);
//                if (info.getCode()==0){
//
//                    Map<String,Object> skuInfo = (Map<String, Object>) info.get("skuInfo");
//
//                    wareSkuEntity.setSkuName((String) skuInfo.get("skuName"));
//                }

            }catch (Exception e){
                e.printStackTrace();
            }

            this.save(wareSkuEntity);

        } else {
            wareSkuDao.UpdateWareStack(skuId,wareId,skuNum);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuId) {

        List<SkuHasStockVo> skuHasStockVos = skuId.stream().map(item -> {

            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();

            Long sumStock = baseMapper.getSkuHasStock(item);

            skuHasStockVo.setSkuId(item);
            skuHasStockVo.setHasStock(sumStock==null?false:sumStock>0);

            return skuHasStockVo;

        }).collect(Collectors.toList());

        return skuHasStockVos;
    }

    //锁库存
    @Transactional
    @Override
    public Boolean orderStockLock(WareSkuLockVo wareSkuLockVo) {

        /**
         * 保存库存工作单的详情。
         * 追溯。
         */
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(wareSkuLockVo.getOrderSn());
        wareOrderTaskService.save(taskEntity);


        //按照下单的收货地址，找到一个就近仓库，锁定库存
        List<OrderItemVo> locks = wareSkuLockVo.getLocks();
        //找到每个商品在哪个仓库都有库存
        List<SkuWareHasStock> collect = locks.stream().map((item) -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();

            stock.setNum(item.getCount());
            stock.setSkuId(skuId);
            //查询这个商品在哪里有库存
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareIds);

            return stock;
        }).collect(Collectors.toList());

        for (SkuWareHasStock hasStock : collect) {

            Boolean skuStocked =false;

            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            if(wareIds == null && wareIds.size() == 0){
                throw new NostockException(skuId);
            }
            //远程锁库存  成功返回1，失败返回0
            for (Long wareId : wareIds) {
                Long count = wareSkuDao.lockSkuStock(skuId,wareId,hasStock.getNum());
                if(count == 1){
                    skuStocked = true;
                    // 告诉MQ库存锁定成功
                    WareOrderTaskDetailEntity taskDetailEntity = new WareOrderTaskDetailEntity(null, skuId, "", hasStock.getNum(), taskEntity.getId(), wareId, 1);
                    wareOrderTaskDetailService.save(taskDetailEntity);

                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setId(taskEntity.getId());

                    stockDetailTo stockDetailTo = new stockDetailTo();
                    BeanUtils.copyProperties(taskDetailEntity,stockDetailTo);

                    lockedTo.setDetailTo(stockDetailTo);

                    rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",lockedTo);

                    break;
                }else {

                }
            }
            if (skuStocked == false){
                throw new NostockException(skuId);
            }

        }

        return true;
    }

    @Override
    public void unlockStock(StockLockedTo to) {

        Long id = to.getId();

        stockDetailTo detailTo = to.getDetailTo();
        Long detailToId = detailTo.getId();

        WareOrderTaskDetailEntity byId = wareOrderTaskDetailService.getById(detailToId);

        if(byId != null){
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();
            R r = orderRPCService.getOrderStatus(orderSn);
            if(r.getCode() == 0){

                OrderVo data = r.getData(new TypeReference<OrderVo>() {
                });
                if(data == null || data.getStatus() == 4){
                    //订单不存在
                    //订单已经被取销了，才能解锁库存
                    if(byId.getLockStatus() == 1){
                        unLockStock(detailTo.getSkuId(),detailTo.getWareId(),detailTo.getSkuNum(),id);
                    }
                }
            }else{
                //消息拒绝以后重新放回到队列里面，让别人继续消费解锁
                throw new RuntimeException("远程服务失败");
            }
        }else{
            //无需解锁
        }
    }

    @Override
    public void CloseStock(OrderTo to) {

        String orderSn = to.getOrderSn();

        //查下最新库存的状态，防止重复解锁库存
        WareOrderTaskEntity wareOrderTaskEntity = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);

        Long id = wareOrderTaskEntity.getId();
        //按照工作单找到所有 没有解锁的库存，进行解锁
        List<WareOrderTaskDetailEntity> list = wareOrderTaskDetailService.list(
                new QueryWrapper<WareOrderTaskDetailEntity>().
                        eq("task_id", id).eq("lock_status", 1));

        for (WareOrderTaskDetailEntity entity :list) {
            unLockStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum(),entity.getId());
        }

    }

    private void unLockStock(Long skuId, Long wareId, Integer skuNum, Long detailTo) {

        Long aLong = wareSkuDao.unLockStock(skuId, wareId, skuNum);
        System.out.println(aLong);
        WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity();
        entity.setLockStatus(2);
        entity.setId(detailTo);
        wareOrderTaskDetailService.updateById(entity);

    }

    @Data
    class SkuWareHasStock{

        private Long skuId;
        private Integer num;
        private List<Long> wareId;

    }

}












